/**
 * @author Vitor Franco do Carmo (vitor.carmo@capgemini.com)
 * @since 28/03/2013
 *
 */
package br.com.vfcfw.controller.converter;

import javax.faces.bean.ApplicationScoped;
import javax.faces.bean.ManagedBean;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.FacesConverter;

import br.com.vfcfw.commons.util.StringUtil;

/**
 * Conversor de CNPJ.
 * 
 * @author Vitor Franco do Carmo (vitor.carmo@capgemini.com)
 * @since 28/03/2013
 * 
 */
@FacesConverter("converter.cnpjConverter")
@ManagedBean(name = "cnpjConverter", eager = true)
@ApplicationScoped
public class CnpjConverter extends BaseConverter {

    /**
     * Construtor da classe.
     */
    public CnpjConverter() {

        super();
    }

    /**
     * Retorna o CNPJ sem a máscara. {@inheritDoc}
     * 
     * @see javax.faces.convert.Converter#getAsObject(javax.faces.context.FacesContext,
     *      javax.faces.component.UIComponent, java.lang.String)
     */
    @Override
    public Object getAsObject(FacesContext context, UIComponent componente, String valor) {

        String cnpj = valor;

        if (possuiValor(valor)) {

            cnpj = StringUtil.removerMascaraNumerica(valor);
        }
        return cnpj;
    }

    /**
     * Retorna o CNPJ com a máscara. {@inheritDoc}
     * 
     * @see javax.faces.convert.Converter#getAsString(javax.faces.context.FacesContext,
     *      javax.faces.component.UIComponent, java.lang.Object)
     */
    @Override
    public String getAsString(FacesContext context, UIComponent componente, Object valor) {

        String cnpj = (String) valor;

        if (possuiValor(cnpj) && cnpj.length() == 14) {

            cnpj = StringUtil.inserirMascara(valor.toString(), "##.###.###/####-##");
        }
        return cnpj;
    }

}
